from socket import socket, SOCK_STREAM, AF_INET
from base64 import b64encode
from json import dumps
from threading import Thread


def main():
    # èªå®ä¹çº¿ç¨ç±»
    class FileTransferHandler(Thread):

        def __init__(self, cclient):
            super().__init__()
            self.cclient = cclient

        def run(self):
            my_dict = {}
            my_dict['filename'] = 'guido.jpg'
            # JSONæ¯çº¯ææ¬ä¸è½æºå¸¦äºè¿å¶æ°æ®
            # æä»¥å¾ççäºè¿å¶æ°æ®è¦å¤çæbase64ç¼ç 
            my_dict['filedata'] = data
            # éè¿dumpså½æ°å°å­å¸å¤çæJSONå­ç¬¦ä¸²
            json_str = dumps(my_dict)
            # åéJSONå­ç¬¦ä¸²
            self.cclient.send(json_str.encode('utf-8'))
            self.cclient.close()

    # 1.åå»ºå¥æ¥å­å¯¹è±¡å¹¶æå®ä½¿ç¨åªç§ä¼ è¾æå¡
    server = socket()
    # 2.ç»å®IPå°ååç«¯å£(åºåä¸åçæå¡)
    server.bind(('192.168.1.2', 5566))
    # 3.å¼å¯çå¬ - çå¬å®¢æ·ç«¯è¿æ¥å°æå¡å¨
    server.listen(512)
    print('æå¡å¨å¯å¨å¼å§çå¬...')
    with open('guido.jpg', 'rb') as f:
        # å°äºè¿å¶æ°æ®å¤çæbase64åè§£ç æå­ç¬¦ä¸²
        data = b64encode(f.read()).decode('utf-8')
    while True:
        client, addr = server.accept()
        # å¯å¨ä¸ä¸ªçº¿ç¨æ¥å¤çå®¢æ·ç«¯çè¯·æ±
        FileTransferHandler(client).start()


if __name__ == '__main__':
    main()